//
//  ViewController.m
//  mupeerConnection客户端
//
//  Created by MyMac on 15/9/11.
//  Copyright (c) 2015年 tongfang. All rights reserved.
//

#import "ViewController.h"
#import <MultipeerConnectivity/MultipeerConnectivity.h>
@interface ViewController ()<MCSessionDelegate,MCBrowserViewControllerDelegate>
@property(nonatomic,strong)MCSession*session;
@property (weak, nonatomic) IBOutlet UIImageView *messageImage;
@property(nonatomic,strong)MCBrowserViewController*browserController;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    MCPeerID*peerID=[[MCPeerID alloc]initWithDisplayName:@"客户端连接"];
    self.session=[[MCSession alloc]initWithPeer:peerID];
    self.session.delegate=self;
}
- (IBAction)sendImage:(id)sender {
    
    UIImage*image=[UIImage imageNamed:@"屏幕快照 2015-09-11 下午4.43.20"];
    NSError*error=nil;
     [self.session sendData:UIImagePNGRepresentation(image) toPeers:[self.session connectedPeers] withMode:MCSessionSendDataUnreliable error:&error];
}
- (IBAction)nearlySelect:(id)sender {
    self.browserController=[[MCBrowserViewController alloc]initWithServiceType:@"cmj-stream" session:self.session];
    self.browserController.delegate=self;
    [self presentViewController:self.browserController animated:YES completion:nil];
}

#pragma mark - MCBrowserViewController代理方法
-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController{
    NSLog(@"已选择");
    [self.browserController dismissViewControllerAnimated:YES completion:nil];
}
-(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController{
    NSLog(@"取消浏览.");
    [self.browserController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - MCSession代理方法
-(void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state{
    NSLog(@"didChangeState");
    switch (state) {
        case MCSessionStateConnected:
            NSLog(@"连接成功.");
            [self.browserController dismissViewControllerAnimated:YES completion:nil];
            break;
        case MCSessionStateConnecting:
            NSLog(@"正在连接...");
            break;
        default:
            NSLog(@"连接失败.");
            break;
    }
}
//接收数据
-(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID{
    NSLog(@"开始接收数据...");
    UIImage *image=[UIImage imageWithData:data];
    [self.messageImage setImage:image];
    //保存到相册
   // UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
